from flask import request, g
from ..model.User import User
from ..utils.db import db
from ..utils.files.avatarUtils import getRandomAvatar
from ..utils.tempName import randName


def __insertUserInfo():
    utoken = request.headers.get("x-token-utoken")
    gToken = request.headers.get("x-token-gtoken")
    if utoken is None or utoken == '':
        user = User.query.filter(User.token == gToken).filter(User.type == 0).first()
        if user is None:
            user = User(token=gToken, avatar=getRandomAvatar(gToken), name=randName(gToken))
            db.session.add(user)
            db.session.commit()
    else:
        user = User.query.filter(User.token == gToken).filter(User.type != 0)
    g.user = {"name": user.name, "avatar": user.avatar, "role": user.type, "id": user.id}


def userInfo(f):
    def wrapF(*args, **kwargs):
        __insertUserInfo()
        return f(*args, **kwargs)

    return wrapF
